package handler

import (
	"essay/api/request"
	"essay/internal/dao"
	"essay/internal/models"
	"github.com/gin-gonic/gin"
)

func CreateEssay(c *gin.Context) {
	var req request.CreateEssayReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var essay models.Essays
	dao.GetOneByFields(&models.Essays{EssayTitle: req.EssayTitle}, &essay)
	if req.EssayInfo == "" {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "文章标题不能为空",
			"data": nil,
		})
		return
	}
	essays := models.Essays{
		UserId:     uint64(c.GetUint("userId")),
		EssayTitle: req.EssayTitle,
		EssayInfo:  req.EssayInfo,
	}
	if !dao.Create(&essays) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "文章发布失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "文章发布成功",
		"data": essays.EssayTitle,
	})
}

func QueryEssay(c *gin.Context) {
	var req request.QueryEssayReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var essay models.Essays
	dao.GetOneById(uint(req.Id), &essay)
	if essay.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "文章不存在",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": essay,
	})
}
